<template>
  <div class="panel-tab__content">
    <el-form label-width="90px" @submit.native.prevent>
      <el-form-item label="表单" prop="formKey">
        <el-select v-model="formKey" placeholder="请选择表单" @change="updateElementFormKey" clearable>
          <el-option v-for="item in formOptions" :key="item.formId" :label="item.formName" :value="`key_${item.formId}`" />
        </el-select>
      </el-form-item>
      <el-form-item prop="localScope">
        <template #label>
          <el-tooltip content="若为节点表单，则表单信息仅在此节点可用，默认为全局表单，表单信息在整个流程实例中可用" placement="top-start">
            <el-icon><InfoFilled /></el-icon>
          </el-tooltip>
          <span>节点表单</span>
        </template>
        <el-switch :disabled="type === 'StartEvent'" v-model="localScope" active-text="是" inactive-text="否" @change="updateElementFormScope()" />
      </el-form-item>
<!--      <el-form-item label="表单标识">-->
<!--        <el-input v-model="formKey" clearable @change="updateElementFormKey" />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="业务标识">-->
<!--        <el-select v-model="businessKey" @change="updateElementBusinessKey">-->
<!--          <el-option v-for="i in fieldList" :key="i.id" :value="i.id" :label="i.label" />-->
<!--          <el-option label="无" value="" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
    </el-form>

    <!--字段列表-->
<!--    <div class="element-property list-property">-->
<!--      <el-divider><i class="el-icon-coin"></i> 表单字段</el-divider>-->
<!--      <el-table :data="fieldList" size="small" max-height="240" border fit>-->
<!--        <el-table-column label="序号" type="index" width="50px" />-->
<!--        <el-table-column label="字段名称" prop="label" min-width="80px" show-overflow-tooltip />-->
<!--        <el-table-column label="字段类型" prop="type" min-width="80px" :formatter="row => fieldType[row.type] || row.type" show-overflow-tooltip />-->
<!--        <el-table-column label="默认值" prop="defaultValue" min-width="80px" show-overflow-tooltip />-->
<!--        <el-table-column label="操作" width="90px">-->
<!--          <template #default="{ row, $index }">-->
<!--            <el-button size="small" type="text" @click="openFieldForm(row, $index)">编辑</el-button>-->
<!--            <el-divider direction="vertical" />-->
<!--            <el-button size="small" type="text" style="color: #ff4d4f" @click="removeField(row, $index)">移除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
<!--    </div>-->
<!--    <div class="element-drawer__button">-->
<!--      <el-button size="small" type="primary" icon="el-icon-plus" @click="openFieldForm(null, -1)">添加字段</el-button>-->
<!--    </div>-->

    <!--字段配置侧边栏-->
<!--    <el-drawer v-model="fieldModelVisible" title="字段配置" :size="`${width}px`" append-to-body destroy-on-close>-->
<!--      <el-form :model="formFieldForm" label-width="90px" size="small" @submit.native.prevent>-->
<!--        <el-form-item label="字段ID">-->
<!--          <el-input v-model="formFieldForm.id" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="类型">-->
<!--          <el-select v-model="formFieldForm.typeType" placeholder="请选择字段类型" clearable @change="changeFieldTypeType">-->
<!--            <el-option v-for="(value, key) of fieldType" :label="value" :value="key" :key="key" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="类型名称" v-if="formFieldForm.typeType === 'custom'">-->
<!--          <el-input v-model="formFieldForm.type" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="名称">-->
<!--          <el-input v-model="formFieldForm.label" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="时间格式" v-if="formFieldForm.typeType === 'date'">-->
<!--          <el-input v-model="formFieldForm.datePattern" clearable />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="默认值">-->
<!--          <el-input v-model="formFieldForm.defaultValue" clearable />-->
<!--        </el-form-item>-->
<!--      </el-form>-->

<!--      &lt;!&ndash; 枚举值设置 &ndash;&gt;-->
<!--      <template v-if="formFieldForm.type === 'enum'">-->
<!--        <el-divider key="enum-divider" />-->
<!--        <p class="listener-filed__title" key="enum-title">-->
<!--          <span><i class="el-icon-menu"></i>枚举值列表：</span>-->
<!--          <el-button size="small" type="primary" @click="openFieldOptionForm(null, -1, 'enum')">添加枚举值</el-button>-->
<!--        </p>-->
<!--        <el-table :data="fieldEnumList" size="small" key="enum-table" max-height="240" border fit>-->
<!--          <el-table-column label="序号" width="50px" type="index" />-->
<!--          <el-table-column label="枚举值编号" prop="id" min-width="100px" show-overflow-tooltip />-->
<!--          <el-table-column label="枚举值名称" prop="name" min-width="100px" show-overflow-tooltip />-->
<!--          <el-table-column label="操作" width="90px">-->
<!--            <template #default="{ row, $index }">-->
<!--              <el-button size="small" type="text" @click="openFieldOptionForm(row, $index, 'enum')">编辑</el-button>-->
<!--              <el-divider direction="vertical" />-->
<!--              <el-button size="small" type="text" style="color: #ff4d4f" @click="removeFieldOptionItem(row, $index, 'enum')">移除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
<!--      </template>-->

<!--      &lt;!&ndash; 校验规则 &ndash;&gt;-->
<!--      <el-divider key="validation-divider" />-->
<!--      <p class="listener-filed__title" key="validation-title">-->
<!--        <span><i class="el-icon-menu"></i>约束条件列表：</span>-->
<!--        <el-button size="small" type="primary" @click="openFieldOptionForm(null, -1, 'constraint')">添加约束</el-button>-->
<!--      </p>-->
<!--      <el-table :data="fieldConstraintsList" size="small" key="validation-table" max-height="240" border fit>-->
<!--        <el-table-column label="序号" width="50px" type="index" />-->
<!--        <el-table-column label="约束名称" prop="name" min-width="100px" show-overflow-tooltip />-->
<!--        <el-table-column label="约束配置" prop="config" min-width="100px" show-overflow-tooltip />-->
<!--        <el-table-column label="操作" width="90px">-->
<!--          <template #default="{ row, $index }">-->
<!--            <el-button size="small" type="text" @click="openFieldOptionForm(row, $index, 'constraint')">编辑</el-button>-->
<!--            <el-divider direction="vertical" />-->
<!--            <el-button size="small" type="text" style="color: #ff4d4f" @click="removeFieldOptionItem(row, $index, 'constraint')">移除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->

<!--      &lt;!&ndash; 表单属性 &ndash;&gt;-->
<!--      <el-divider key="property-divider" />-->
<!--      <p class="listener-filed__title" key="property-title">-->
<!--        <span><i class="el-icon-menu"></i>字段属性列表：</span>-->
<!--        <el-button size="small" type="primary" @click="openFieldOptionForm(null, -1, 'property')">添加属性</el-button>-->
<!--      </p>-->
<!--      <el-table :data="fieldPropertiesList" size="small" key="property-table" max-height="240" border fit>-->
<!--        <el-table-column label="序号" width="50px" type="index" />-->
<!--        <el-table-column label="属性编号" prop="id" min-width="100px" show-overflow-tooltip />-->
<!--        <el-table-column label="属性值" prop="value" min-width="100px" show-overflow-tooltip />-->
<!--        <el-table-column label="操作" width="90px">-->
<!--          <template #default="{ row, $index }">-->
<!--            <el-button size="small" type="text" @click="openFieldOptionForm(row, $index, 'property')">编辑</el-button>-->
<!--            <el-divider direction="vertical" />-->
<!--            <el-button size="small" type="text" style="color: #ff4d4f" @click="removeFieldOptionItem(row, $index, 'property')">移除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->

<!--      &lt;!&ndash; 底部按钮 &ndash;&gt;-->
<!--      <div class="element-drawer__button">-->
<!--        <el-button size="small">取 消</el-button>-->
<!--        <el-button size="small" type="primary" @click="saveField">保 存</el-button>-->
<!--      </div>-->
<!--    </el-drawer>-->

    <el-dialog v-model="fieldOptionModelVisible" :title="optionModelTitle" width="600px" append-to-body destroy-on-close>
      <el-form :model="fieldOptionForm" size="small" label-width="96px" @submit.native.prevent>
        <el-form-item label="编号/ID" v-if="fieldOptionType !== 'constraint'" key="option-id">
          <el-input v-model="fieldOptionForm.id" clearable />
        </el-form-item>
        <el-form-item label="名称" v-if="fieldOptionType !== 'property'" key="option-name">
          <el-input v-model="fieldOptionForm.name" clearable />
        </el-form-item>
        <el-form-item label="配置" v-if="fieldOptionType === 'constraint'" key="option-config">
          <el-input v-model="fieldOptionForm.config" clearable />
        </el-form-item>
        <el-form-item label="值" v-if="fieldOptionType === 'property'" key="option-value">
          <el-input v-model="fieldOptionForm.value" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="fieldOptionModelVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="saveFieldOption">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ElementForm">
import { onMounted } from 'vue'

// import { listForm } from "@/api/workflow/form";

const {proxy} = getCurrentInstance()

const props = defineProps({
  id: String,
  type: String
})
const {id,type} = toRefs(props)

const prefix = inject('prefix')
const width = inject('width')

const state = reactive({
  formOptions: [],
  formKey: "",
  localScope: false,
  businessKey: "",
  optionModelTitle: "",
  fieldList: [],
  formFieldForm: {},
  fieldType: {
    long: "长整型",
    string: "字符串",
    boolean: "布尔类",
    date: "日期类",
    enum: "枚举类",
    custom: "自定义类型"
  },
  formFieldIndex: -1, // 编辑中的字段， -1 为新增
  formFieldOptionIndex: -1, // 编辑中的字段配置项， -1 为新增
  fieldModelVisible: false,
  fieldOptionModelVisible: false,
  fieldOptionForm: {}, // 当前激活的字段配置项数据
  fieldOptionType: "", // 当前激活的字段配置项弹窗 类型
  fieldEnumList: [], // 枚举值列表
  fieldConstraintsList: [], // 约束条件列表
  fieldPropertiesList: [], // 绑定属性列表
  bpmnELement: undefined,
  otherExtensions: undefined,
  formData: undefined
})
const {formOptions,formKey,localScope,businessKey,optionModelTitle,fieldList,formFieldForm,
  fieldType,formFieldIndex,formFieldOptionIndex,fieldModelVisible,fieldOptionModelVisible,
  fieldOptionForm,fieldOptionType,fieldEnumList,fieldConstraintsList,fieldPropertiesList,bpmnELement} = toRefs(state)

watch(()=>props.id,(val) => {
  val && val.length && proxy.$nextTick(() => resetFormList());
},{immediate: true})
onMounted(() => {
  getFormList()
})
/** 查询表单列表 */
function getFormList() {
  // listForm().then(response => this.formOptions = response.rows)
}
function resetFormList() {
  state.bpmnELement = window.bpmnInstances.bpmnElement;
  state.formKey = state.bpmnELement.businessObject.formKey;
  state.localScope = state.bpmnELement.businessObject.localScope;
  // 获取元素扩展属性 或者 创建扩展属性
  let elExtensionElements =
    state.bpmnELement.businessObject.get("extensionElements") || window.bpmnInstances.moddle.create("bpmn:ExtensionElements", { values: [] });
  // 获取元素表单配置 或者 创建新的表单配置
  // this.formData =
  //   this.elExtensionElements.values.filter(ex => ex.$type === `${this.prefix}:FormData`)?.[0] ||
  //   window.bpmnInstances.moddle.create(`${this.prefix}:FormData`, { fields: [] });
  // 业务标识 businessKey， 绑定在 formData 中
  // this.businessKey = this.formData.businessKey;

  // 保留剩余扩展元素，便于后面更新该元素对应属性
  state.otherExtensions = elExtensionElements.values.filter(ex => ex.$type !== `${prefix}:FormData`);

  // 复制原始值，填充表格
  // this.fieldList = JSON.parse(JSON.stringify(this.formData.fields || []));

  // 更新元素扩展属性，避免后续报错
  // this.updateElementExtensions();
}
function updateElementFormKey() {
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), { formKey: state.formKey });
}
function updateElementFormScope() {
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), { localScope: state.localScope });
}
function updateElementBusinessKey() {
  window.bpmnInstances.modeling.updateModdleProperties(toRaw(state.bpmnElement), state.formData, { businessKey: state.businessKey });
}
// 根据类型调整字段type
function changeFieldTypeType(type) {
  state.formFieldForm.type = type === "custom" ? "" : type
}
// 打开字段详情侧边栏
function openFieldForm(field, index) {
  state.formFieldIndex = index;
  if (index !== -1) {
    const FieldObject = state.formData.fields[index];
    state.formFieldForm = JSON.parse(JSON.stringify(field));
    // 设置自定义类型
    state.formFieldForm.typeType = !state.fieldType[field.type] ? "custom" : field.type
    // 初始化枚举值列表
    field.type === "enum" && (state.fieldEnumList = JSON.parse(JSON.stringify(FieldObject?.values || [])));
    // 初始化约束条件列表
    state.fieldConstraintsList = JSON.parse(JSON.stringify(FieldObject?.validation?.constraints || []));
    // 初始化自定义属性列表
    state.fieldPropertiesList = JSON.parse(JSON.stringify(FieldObject?.properties?.values || []));
  } else {
    state.formFieldForm = {};
    // 初始化枚举值列表
    state.fieldEnumList = [];
    // 初始化约束条件列表
    state.fieldConstraintsList = [];
    // 初始化自定义属性列表
    state.fieldPropertiesList = [];
  }
  state.fieldModelVisible = true;
}
// 打开字段 某个 配置项 弹窗
function openFieldOptionForm(option, index, type) {
  state.fieldOptionModelVisible = true;
  state.fieldOptionType = type;
  state.formFieldOptionIndex = index;
  if (type === "property") {
    state.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {};
    return (state.optionModelTitle = "属性配置");
  }
  if (type === "enum") {
    state.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {};
    return (state.optionModelTitle = "枚举值配置");
  }
  state.fieldOptionForm = option ? JSON.parse(JSON.stringify(option)) : {};
  return (state.optionModelTitle = "约束条件配置");
}
// 保存字段 某个 配置项
function saveFieldOption() {
  if (state.formFieldOptionIndex === -1) {
    if (state.fieldOptionType === "property") {
      state.fieldPropertiesList.push(state.fieldOptionForm);
    }
    if (state.fieldOptionType === "constraint") {
      state.fieldConstraintsList.push(state.fieldOptionForm);
    }
    if (state.fieldOptionType === "enum") {
      state.fieldEnumList.push(state.fieldOptionForm);
    }
  } else {
    state.fieldOptionType === "property" && state.fieldPropertiesList.splice(state.formFieldOptionIndex, 1, state.fieldOptionForm);
    state.fieldOptionType === "constraint" && state.fieldConstraintsList.splice(state.formFieldOptionIndex, 1, state.fieldOptionForm);
    state.fieldOptionType === "enum" && state.fieldEnumList.splice(state.formFieldOptionIndex, 1, state.fieldOptionForm);
  }
  state.fieldOptionModelVisible = false;
  state.fieldOptionForm = {};
}
// 保存字段配置
function saveField() {
  const { id, type, label, defaultValue, datePattern } = state.formFieldForm;
  const Field = window.bpmnInstances.moddle.create(`${prefix}:FormField`, { id, type, label });
  defaultValue && (Field.defaultValue = defaultValue);
  datePattern && (Field.datePattern = datePattern);
  // 构建属性
  if (state.fieldPropertiesList && state.fieldPropertiesList.length) {
    const fieldPropertyList = state.fieldPropertiesList.map(fp => {
      return window.bpmnInstances.moddle.create(`${prefix}:Property`, { id: fp.id, value: fp.value });
    });
    Field.properties = window.bpmnInstances.moddle.create(`${prefix}:Properties`, { values: fieldPropertyList });
  }
  // 构建校验规则
  if (state.fieldConstraintsList && state.fieldConstraintsList.length) {
    const fieldConstraintList = state.fieldConstraintsList.map(fc => {
      return window.bpmnInstances.moddle.create(`${prefix}:Constraint`, { name: fc.name, config: fc.config });
    });
    Field.validation = window.bpmnInstances.moddle.create(`${prefix}:Validation`, { constraints: fieldConstraintList });
  }
  // 构建枚举值
  if (state.fieldEnumList && state.fieldEnumList.length) {
    Field.values = state.fieldEnumList.map(fe => {
      return window.bpmnInstances.moddle.create(`${prefix}:Value`, { name: fe.name, id: fe.id });
    });
  }
  // 更新数组 与 表单配置实例
  if (state.formFieldIndex === -1) {
    state.fieldList.push(state.formFieldForm);
    state.formData.fields.push(Field);
  } else {
    state.fieldList.splice(state.formFieldIndex, 1, state.formFieldForm);
    state.formData.fields.splice(state.formFieldIndex, 1, Field);
  }
  updateElementExtensions();
  state.fieldModelVisible = false;
}
// 移除某个 字段的 配置项
function removeFieldOptionItem(option, index, type) {
  if (type === "property") {
    state.fieldPropertiesList.splice(index, 1);
    return;
  }
  if (type === "enum") {
    state.fieldEnumList.splice(index, 1);
    return;
  }
  state.fieldConstraintsList.splice(index, 1);
}
// 移除 字段
function removeField(field, index) {
  state.fieldList.splice(index, 1);
  state.formData.fields.splice(index, 1);
  updateElementExtensions();
}
function updateElementExtensions() {
  // 更新回扩展元素
  const newElExtensionElements = window.bpmnInstances.moddle.create(`bpmn:ExtensionElements`, {
    values: state.otherExtensions.concat(state.formData)
  });
  // 更新到元素上
  window.bpmnInstances.modeling.updateProperties(toRaw(state.bpmnElement), {
    extensionElements: newElExtensionElements
  });
}

</script>
